import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';

import {
    GridComponent,
    DatasetComponent,
    LegendComponent
} from 'echarts/components';

echarts.use([
    GridComponent,
    TitleComponent,
    TooltipComponent,
    DatasetComponent,
    LegendComponent,
    BarChart,
    CanvasRenderer
]);

echarts.use([TitleComponent, TooltipComponent, BarChart, CanvasRenderer, PieChart]);

const EChartsComponent = () => {
    const chartRef = useRef(null);
    const chartInstance = useRef(null); // 用于存储图表实例

    useEffect(() => {
        const chart = echarts.init(chartRef.current);

        // 初始化图表实例
        chartInstance.current = chart;

        const option = {
            legend: {},
            tooltip: {},
            dataset: {
                dimensions: ['product', '内科综合', '外科综合', '超声科'],
                source: [
                    { product: '本周权重', '内科综合': 20, '外科综合': 20, '超声科': 54 },
                    { product: '本月权重', '内科综合': 30, '外科综合': 35, '超声科': 43 },
                    { product: '季度权重', '内科综合': 40, '外科综合': 54, '超声科': 56 },
                    { product: '年度权重', '内科综合': 55, '外科综合': 60, '超声科': 56 }
                ]
            },
            xAxis: { type: 'category' },
            yAxis: {},
            // Declare several bar series, each will be mapped
            // to a column of dataset.source by default.
            series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }]
        };

        chart.setOption(option);
        // 监听容器大小变化
        const resizeObserver = new ResizeObserver(() => {
            chart.resize();
        });
        resizeObserver.observe(chartRef.current);

        return () => {
            chart.dispose();
            resizeObserver.disconnect();
        };
    }, []);

    return <div ref={chartRef} style={{ width: '40vw', height: '400px', maxWidth: '40vw', maxHeight: '400px' }}></div>;
};

export default EChartsComponent;

